package com.LJH.WebTask4.controller;

import com.LJH.WebTask4.mybatis.entity.Book;
import com.LJH.WebTask4.mybatis.mapper.BookMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@SessionAttributes("bookList")
public class BkListController {
    @Resource
    BookMapper bookMapper;

    @GetMapping("/booklist")
    public String getBookList(Model model) {
        List<Book> bookList = bookMapper.selectAll();
        model.addAttribute("bookList", bookList);
        return "BookList";
    }

    @GetMapping("/register")
    public String registerForm() {
        return "Registration";
    }

    @PostMapping("/register")
    public String register(@RequestParam String bookName,
                           @RequestParam String author,
                           @RequestParam String press,
                           @RequestParam String publicDate,
                           @RequestParam int surplus) {
        Book book = new Book(bookName, author, press, publicDate, surplus);
        bookMapper.insert(book);
        return "Registration";
    }

    @GetMapping("/delete")
    public String delete(@RequestParam int index) {
        bookMapper.deleteById(index);
        return "redirect:/booklist";
    }

    @GetMapping("/edit")
    public String editForm(Model model, @RequestParam int index) {
        Book book = bookMapper.selectById(index);
        model.addAttribute("book", book);
        return "Edit";
    }

    @PostMapping("/edit")
    public String edit(@ModelAttribute Book book) {
        bookMapper.update(book);
        return "redirect:/booklist";
    }
}
